package com.morningstar.system.websocket;

import cn.dev33.satoken.exception.SaTokenException;
import cn.dev33.satoken.stp.StpUtil;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Slf4j
@Component
@ServerEndpoint("/ws/message/{token}")
public class MessageEndPoint {

    /**
     * 连接成功
     *
     * @param session session
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        Object userId = StpUtil.getLoginIdByToken(token);
        if (userId == null) {
            throw new SaTokenException("token无效");
        }
        log.info("连接成功 {}", token);
    }

    /**
     * 连接关闭
     *
     * @param session session
     */
    @OnClose
    public void onClose(Session session) {
        log.info("连接关闭");
    }

    /**
     * 接收到消息
     *
     * @param token token
     */
    @OnMessage
    public String onMessage(String token) throws IOException {
        Object userId = StpUtil.getLoginIdByToken(token);
        if (userId == null) {
            throw new SaTokenException("token无效");
        }
        return "servet 发送：" + token;
    }
}
